package com.crud.controller;

import com.crud.entity.Book;
import com.crud.service.BookService;
import com.crud.util.StringRemoveSpacesUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/book")
public class BookController {
    //controller调用service
    @Resource(name = "bookService")
    private BookService bookService;

    @RequestMapping("/allBook")
    public String list(Model model){
        List<Book> books = bookService.queryAllBooks();
        model.addAttribute("books",books);
        return "allBook";
    }

    //跳转到增加书籍页面
    @RequestMapping("/toAddBook")
    public String toAddBook(){
        return "addBook";
    }

    //添加书籍请求
    @RequestMapping("/addBook")
    public String addBook(Book book){
        bookService.addBook(book);
        return "redirect:/book/allBook";//重定向到我们的请求@RequestMapping("/allBook")请求复用
    }
    //跳转到修改页面
    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(Integer id,Model model){
        model.addAttribute("book",bookService.queryBookById(id));
        return "updateBook";
    }
    //修改书籍信息
    @RequestMapping("/updateBook")
    public String updateBook(Book book){
        bookService.updateBook(book);
        return "redirect:/book/allBook";
    }
    //删除书籍 rest风格
    /*@RequestMapping("/delBook/{id}")
    public String delBook(@PathVariable("id") Integer id){
        bookService.delBookById(id);
        return "redirect:/book/allBook";
    }*/
    /*ajax实现删除*/
    @RequestMapping("/delBook")
    @ResponseBody
    public String delBook(Integer bookID){
        if (bookService.delBookById(bookID))
            return "true";
        return "false";
    }
    //查询书籍名称
    @RequestMapping("/queryBookName")
    public String queryBookName(String bookName,Model model){
        //字符串去除空格
        bookName = StringRemoveSpacesUtil.removeSpaces(bookName);
        List<Book> books = bookService.queryBookByName(bookName);
        if (books.size()!=0){
            model.addAttribute("books",books);
        }else {
            model.addAttribute("error","没有查询到结果");
        }
        return "allBook";
    }
}
